package com.guigu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.util.StringUtil;
import com.guigu.mapper.*;
import com.guigu.pojo.*;
import com.guigu.service.DeliveryAddressService;
import com.guigu.service.SupplierSupplyOfGoodsService;
import com.guigu.service.UsersService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    //自动注入
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    DeliveryAddressMapper deliveryAddressMapper;
    @Autowired
    SupplierSupplyOfGoodsMapper supplierSupplyOfGoodsMapper;//供应商维护商品表
    @Autowired
    SupplierGoodsCategoryMapper supplierGoodsCategoryMapper;//供应商维护商品分类表
    @Autowired
    ProvinceMapper provinceMapper;//省
    @Autowired
    CityMapper cityMapper;//市
    @Autowired
    RegionMapper regionMapper;//区
    @Autowired
    ShopTypeInfoMapper shopTypeInfoMapper;//商品分类表
    @Autowired
    SystemuUserRoleMapper systemuUserRoleMapper;//系统用户角色表
    @Autowired
    DeliveryAddressService deliveryAddressService;//地址表

    //注册
    @Override
    public Map register(Users users) {

        Map map = new HashMap();

        map.put("msg", "失败");


        if (usersMapper.insert(users) > 0) {
            map.put("msg", "成功");
        }

        return map;
    }

    //判断重复
    @Override
    public Map queryRepetition(Users users) {

        Map map = new HashMap();

        map.put("msg", "未找到");

        QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>();

        if (users.getUName() != null) {
            System.out.println("---------用户名");
            queryWrapper.eq("u_name", users.getUName());

            if (usersMapper.selectCount(queryWrapper) > 0) {
                map.put("msg", "找到了");
            }
        } else {
            map.put("msg", "未找到");
        }


        return map;
    }


    //手机邮箱重复判断
    @Override
    public Map queryRepetition02(Users users) {

        Map map = new HashMap();

        map.put("msg", "未找到");

        QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>();

        if (users.getMailAddress() != null) {
            System.out.println("---------邮箱");
            queryWrapper.eq("mail_address", users.getMailAddress());
        }
        if (users.getPhone() != null) {
            System.out.println("---------手机号");
            queryWrapper.eq("phone", users.getPhone());
        }

        if (users.getPhone() != null || users.getMailAddress() != null) {
            if (usersMapper.selectCount(queryWrapper) > 0) {
                map.put("msg", "找到了");
            }
        } else {
            map.put("msg", "未找到");
        }


        return map;
    }

    //登录
    @Override
    public Users login(Users users) {

        QueryWrapper<Users> queryWrapper = new QueryWrapper();


        if (StringUtils.isNotBlank(users.getMailAddress())) {
            System.out.println("---------邮箱");
            queryWrapper.eq("mail_address", users.getMailAddress());
        }

        if (StringUtils.isNotBlank(users.getPhone())) {
            System.out.println("---------手机号");
            queryWrapper.eq("phone", users.getPhone());
        }
        queryWrapper.eq("u_pwd", users.getUPwd());

        queryWrapper.eq("account_state",0);

        Users users1 = usersMapper.selectOne(queryWrapper);

        return users1;
    }

    //申请成为商户
    @Override
    public Map apply_for_commercial(Users users) {
        System.out.println("结果：" + users);
        Map map = new HashMap();
        //补全属性
        //首先将自提地址对象添加到地址表，获取自增id
        DeliveryAddress deliveryAddress = users.getDeliveryAddressPick();
        deliveryAddressMapper.insert(deliveryAddress);
        //用户id
        users.setId(deliveryAddress.getUId());
        //自提地址id
        users.setAdId(deliveryAddress.getId());
        //将注册商户状态设置为等待审核
        users.setCommercialState(0);
        //进行修改
        if (this.updateById(users)) {
            map.put("msg", "发出申请，等待审核结果");
            map.put("x", true);
        } else {
            map.put("msg", "操作失败");
            map.put("x", false);
        }
        return map;
    }

    //申请成为供应商
    @Override
    public Map apply_for_supplier(Users user, Integer[] supplierGoodsCategoryIds, MultipartFile img, HttpServletRequest request) {
        Map map = new HashMap();
        //为供应商商品分类表循环添加数据
        for (Integer i : supplierGoodsCategoryIds) {
            SupplierGoodsCategory temp_obj = new SupplierGoodsCategory();
            temp_obj.setPId(user.getId());
            temp_obj.setSortId(i);
            supplierGoodsCategoryMapper.insert(temp_obj);
        }
        //补全属性
        //将注册供应商状态设置为等待审核
        user.setSupplierState(0);
        //判断是否上传了图片
        if (img.getSize() > 0) {
            String apppath = request.getServletContext().getRealPath("/upload");
            File file = new File(apppath);
            if (!file.exists()) {
                //不存在就创建
                file.mkdirs();
            }
            //获取文件名称
            String fileName = img.getOriginalFilename();
            //保存文件到路径
            try {
                img.transferTo(new File(apppath, fileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //将路径设置到对象
            user.setBusinessImg("upload/" + fileName);
        }
        //进行修改
        boolean b = this.updateById(user);
        if (b) {
            map.put("msg", "发出申请，等待审核结果");
            map.put("x", true);
        } else {
            map.put("msg", "操作失败");
            map.put("x", false);
        }
        return map;
    }

    //审批商户
    @Override
    public Map audit_for_commercial(Users user) {
        System.out.println("结果：" + user);
        Map map = new HashMap();
        //检查审批是否通过
        if(user.getCommercialState()==2)
        {
            //没能通过，删除该用户对于的地址表数据(自提地址)
            deliveryAddressMapper.deleteById(user.getAdId());
        }
        if(this.updateById(user)){
            map.put("msg","审核成功！");
            map.put("x", true);
            //向系统用户角色表插入一条数据
            SystemuUserRole systemuUserRole = new SystemuUserRole();
            systemuUserRole.setSuId(null);
            systemuUserRole.setUId(user.getId());
            //
            systemuUserRole.setRId(4);
            systemuUserRoleMapper.insert(systemuUserRole);
        }else{
            map.put("msg","操作失败！");
            map.put("x", false);
        }
        return map;
    }

    //审批供应商
    @Override
    public Map audit_for_supplier(Users user) {
        Map map = new HashMap();
        //检查审批是否通过
        if (user.getSupplierState() == 2) {
            //没能通过，删除该用户对于的供应商维护商品分类表的数据
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("p_id", user.getId());
            supplierGoodsCategoryMapper.delete(queryWrapper);
        }
        //进行修改
        if (this.updateById(user)) {
            map.put("msg", "审核成功！");
            map.put("x", true);
            //向系统用户角色表插入一条数据
            SystemuUserRole systemuUserRole = new SystemuUserRole();
            systemuUserRole.setSuId(null);
            systemuUserRole.setUId(user.getId());
            //3为供应商
            systemuUserRole.setRId(3);
            systemuUserRoleMapper.insert(systemuUserRole);
        } else {
            map.put("msg", "操作失败！");
            map.put("x", false);
        }
        return map;
    }

    //分页查询
    @Override
    public Page<Users> queryAllUser(Users users, Integer pageno, Integer pagesize) {
        System.out.println("结果：" + users);
        QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>();
        //条件查询
        //用户名
        if (!StringUtil.isEmpty(users.getUName())) {
            queryWrapper.eq("u_name", users.getUName());
        }
        //注册商户状态
        if (users.getCommercialState() != null) {
            queryWrapper.eq("commercial_state", users.getCommercialState());
        }
        //注册供应商状态
        if (users.getSupplierState() != null) {
            queryWrapper.eq("supplier_state", users.getSupplierState());
        }
        //账号状态
        if (users.getAccountState() != null) {
            queryWrapper.eq("account_state", users.getAccountState());
        }
        Page<Users> page = this.page(new Page<Users>(pageno, pagesize), queryWrapper);
        //循环集合，补全属性
        for (Users u : page.getRecords()) {
            System.out.println("==========对象" + u);
            //检查该用户是否设置了收货地址
            if (u.getReceivingAddressId() != null) {
                //查询地址表，获取该用户的收货地址对象
                DeliveryAddress deliveryAddress = deliveryAddressMapper.selectById(u.getReceivingAddressId());
                //为收货地址对象补全属性
                deliveryAddress.setProvinceName(((Province) (provinceMapper.selectById(deliveryAddress.getPId()))).getName());
                deliveryAddress.setCityName(((City) (cityMapper.selectById(deliveryAddress.getCId()))).getName());
                deliveryAddress.setRegion(((Region) (regionMapper.selectById(deliveryAddress.getRId()))).getName());
                u.setDeliveryAddress(deliveryAddress);
            }
            try {
                //检查该用户是否设置自提地址
                if (u.getAdId() != null) {
                    //查询地址表，获取该用户的自提地址对象
                    DeliveryAddress deliveryAddress = deliveryAddressMapper.selectById(u.getAdId());
                    //为自提地址对象补全属性
                    deliveryAddress.setProvinceName(((Province) (provinceMapper.selectById(deliveryAddress.getPId()))).getName());
                    deliveryAddress.setCityName(((City) (cityMapper.selectById(deliveryAddress.getCId()))).getName());
                    deliveryAddress.setRegion(((Region) (regionMapper.selectById(deliveryAddress.getRId()))).getName());
                    u.setDeliveryAddressPick(deliveryAddress);
                }
            } catch (Exception e) {
                System.out.println("空指针异常");
                System.out.println(e);
            }
            ;
            try {
                //检查用户是否是供应商或者是等待审核的供应商(因为只有成功和等待审核的供应商才有供应商分类表数据)
                if (u.getSupplierState() == 0 || u.getSupplierState() == 1) {
                    //获取该供应商所提供的商品分类名
                    QueryWrapper queryWrapper2 = new QueryWrapper<SupplierGoodsCategory>();
                    queryWrapper2.eq("p_id", u.getId());
                    List<SupplierGoodsCategory> supplierGoodsCategoryList = supplierGoodsCategoryMapper.selectList(queryWrapper2);
                    //循环供应商商品分类表，补全属性
                    String allSupplierGoodsCategoryName = "";
                    for (SupplierGoodsCategory supplierGoodsCategory : supplierGoodsCategoryList) {
                        //查询商品分类表
                        supplierGoodsCategory.setName(shopTypeInfoMapper.selectById(supplierGoodsCategory.getSortId()).getName());
                        //拼接分类名称
                        allSupplierGoodsCategoryName += supplierGoodsCategory.getName() + ",";
                    }
                    u.setSupplierGoodsCategoryName(allSupplierGoodsCategoryName.substring(0, allSupplierGoodsCategoryName.length() - 1));
                    u.setSupplierGoodsCategoryList(supplierGoodsCategoryList);
                }
            } catch (Exception e) {
                System.out.println("空指针异常");
                System.out.println(e);
            }
            try {
                //检查用户是否是商户或者是等待审核的商户
                if (u.getCommercialState() == 0 || u.getCommercialState() == 1) {
                    //获取该商户的自提地址
                    DeliveryAddress deliveryAddress = deliveryAddressMapper.selectById(u.getAdId());
                    //为自提地址补全属性
                    deliveryAddress.setProvinceName(provinceMapper.selectById(deliveryAddress.getPId()).getName());
                    deliveryAddress.setCityName(cityMapper.selectById(deliveryAddress.getCId()).getName());
                    deliveryAddress.setRegion(regionMapper.selectById(deliveryAddress.getRId()).getName());
                    u.setDeliveryAddressPick(deliveryAddress);
                }
            } catch (Exception e) {
                System.out.println("空指针异常");
                System.out.println(e);
            }
        }
        return page;
    }

    //根据id，查询对象
    @Override
    public Users queryUserById(Integer id) {
        Users users = usersMapper.selectById(id);
        //补全属性
        //检查是否是供应商
        try {
            if (users.getSupplierState() != null || users.getSupplierState() == 0 || users.getSupplierState() == 1) {
                //供应商分类集合
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("p_id", id);
                List<SupplierGoodsCategory> supplierGoodsCategoryList = supplierGoodsCategoryMapper.selectList(queryWrapper);
                //循环供应商分类集合，补全属性
                String allSupplierGoodsCategoryName = "";
                for (SupplierGoodsCategory supplierGoodsCategory : supplierGoodsCategoryList) {
                    //查询商品分类表
                    supplierGoodsCategory.setName(shopTypeInfoMapper.selectById(supplierGoodsCategory.getSortId()).getName());
                    //拼接分类名称
                    allSupplierGoodsCategoryName += supplierGoodsCategory.getName() + ",";
                }
                users.setSupplierGoodsCategoryName(allSupplierGoodsCategoryName.substring(0, allSupplierGoodsCategoryName.length() - 1));
                users.setSupplierGoodsCategoryList(supplierGoodsCategoryList);
            }
        } catch (Exception e) {
            System.out.println(e);
            System.out.println("空指针异常。");
        }
        try {
            //检查用户是否是商户或者是等待审核的商户
            if (users.getCommercialState() == 0 || users.getCommercialState() == 1) {
                //获取该商户的自提地址
                DeliveryAddress deliveryAddress = deliveryAddressMapper.selectById(users.getAdId());
                //为自提地址补全属性
                deliveryAddress.setProvinceName(provinceMapper.selectById(deliveryAddress.getPId()).getName());
                deliveryAddress.setCityName(cityMapper.selectById(deliveryAddress.getCId()).getName());
                deliveryAddress.setRegion(regionMapper.selectById(deliveryAddress.getRId()).getName());
                users.setDeliveryAddressPick(deliveryAddress);
            }
        } catch (Exception e) {
            System.out.println("空指针异常");
            System.out.println(e);
        }
        return users;
    }

    //查询商户信息
    @Override
    public Page<Users> queryUsersByTypeId(Users user, Integer pageno, Integer pagesize) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>();
        //查询所有商户
        if (user.getCommercialState() != null) {
            queryWrapper.eq("commercial_state", user.getCommercialState());
        }
        if (StringUtils.isNotBlank(user.getUName())) {
            queryWrapper.like("u_name", user.getUName());

        }
        //查询所有供应商
        if (user.getSupplierState() != null) {
            queryWrapper.eq("supplier_state", user.getSupplierState());
        }
        Page<Users> page = this.page(new Page<Users>(pageno, pagesize), queryWrapper);
        if (user.getCommercialState() != null) {
            //查询商户提供的提货地址
            for (Users obj : page.getRecords()) {
                DeliveryAddress addr = deliveryAddressMapper.selectById(obj.getAdId());
                addr.setProvinceName(provinceMapper.selectById(addr.getPId()).getName());
                addr.setCityName(cityMapper.selectById(addr.getCId()).getName());
                addr.setRegion(regionMapper.selectById(addr.getRId()).getName());
                obj.setDeliveryAddressPick(addr);
            }
        }
        return page;
    }

    //修改用户密码
    @Override
    public Map editUsersbyPwd(Users users) {
        Map map = new HashMap();
        map.put("msg", "修改失败");

        if (usersMapper.updateById(users) > 0) {
            map.put("msg", "修改成功");
        }

        return map;
    }

    //修改用户状态
    @Override
    public Map eideUserbyaccountState(Users users) {
        Map map = new HashMap();
        map.put("msg", "失败");

        Users users1 = usersMapper.selectById(users.getId());

        if (users1.getAccountState() == 0) {
            users.setAccountState(1);
            usersMapper.updateById(users);
            map.put("msg", "成功");
        } else {
            users.setAccountState(0);
            usersMapper.updateById(users);
            map.put("msg", "成功");
        }

        return map;
    }

    //根据id查找员工
    @Override
    public Users usersbyid(Integer id) {
        return usersMapper.selectById(id);
    }

    //修改用户
    @Override
    public Map editusers(Users users, MultipartFile img, HttpServletRequest request) {
        Map map = new HashMap();
        map.put("msg", "修改失败");

        //判断是否上传图片
        if (img != null) {
            String pathName = request.getServletContext().getRealPath("/syUserimgs"); //路径名
            File file = new File(pathName);
            if (!file.exists()) {
                //不存在就创建
                file.mkdirs();
            }
            //获取文件名称
            String fileName = img.getOriginalFilename();
            //保存文件到路径
            try {
                img.transferTo(new File(pathName, fileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //将路径设置到对象
            users.setUsersTopImg("syUserimgs/" + fileName);
        }

        if (usersMapper.updateById(users) > 0) {
            map.put("msg", "修改成功");
        }

        return map;
    }

    @Override
    public Map editcomm(Users users) {
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "编辑失败");
        if (users.getId() != null) {
            Users u = this.getById(users.getId());
            if (u != null) {
                boolean user = this.updateById(users);
                boolean addrs = deliveryAddressMapper.updateById(users.getDeliveryAddressPick()) > 0 ? true : false;
                if (user && addrs) {
                    map.put("code", 1);
                    map.put("msg", "编辑成功");
                }
            }
        }
        return map;
    }

    //绑定手机
    @Override
    public Map userphonebinding(Users users) {
        Map map = new HashMap();
        map.put("msg", "添加失败");

        if (usersMapper.updateById(users) > 0) {
            map.put("msg", "添加成功");
        }
        return map;
    }

    //添加用户
    @Override
    public Map addusers(Users users, MultipartFile img, HttpServletRequest request) {

        Map map = new HashMap();

        map.put("msg", "失败");

        //判断是否上传图片
        if (img != null) {
            String pathName = request.getServletContext().getRealPath("/syUserimgs"); //路径名
            File file = new File(pathName);
            if (!file.exists()) {
                //不存在就创建
                file.mkdirs();
            }
            //获取文件名称
            String fileName = img.getOriginalFilename();
            //保存文件到路径
            try {
                img.transferTo(new File(pathName, fileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //将路径设置到对象
            users.setUsersTopImg("syUserimgs/" + fileName);
        }

        if (usersMapper.insert(users) > 0) {
            map.put("msg", "成功");
        }

        return map;
    }

    @Override
    public Map updateBYisCloseUpShop(Users users) {
        Map map = new HashMap();
        map.put("code", "0");
        map.put("msg", "操作失败");
        if (users.getId() != null && users.getIsCloseUpShop() != null) {
            boolean b = this.updateById(users);
            if (b) {
                map.put("code", "1");
                if (users.getIsCloseUpShop() == 0) {
                    map.put("msg", "开店成功");
                } else {
                    map.put("msg", "打烊成功");
                }
            }
        }

        return map;
    }

    //修改供应商信息(可以修改用户名、密码、自提地址、可提供的分类数据)
    @Override
    public Map updateSupplier(Integer id, String name, Integer[] ids, MultipartFile img, HttpServletRequest request) {
        Map map = new HashMap();
        //根据id，查询用户对象，补全属性
        Users temp_user = usersMapper.selectById(id);
        temp_user.setUName(name);
        //判断是否上传了图片
        if (img != null) {
            if (img.getSize() > 0) {
                String apppath = request.getServletContext().getRealPath("/upload");
                File file = new File(apppath);
                if (!file.exists()) {
                    //不存在就创建
                    file.mkdirs();
                }
                //获取文件名称
                String fileName = img.getOriginalFilename();
                //保存文件到路径
                try {
                    img.transferTo(new File(apppath, fileName));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //将路径设置到对象
                temp_user.setBusinessImg("upload/" + fileName);
            }
        }
        //进行修改
        usersMapper.updateById(temp_user);

        //根据用户id，删除该供应商下的所有可提供的商品分类数据
        QueryWrapper<SupplierGoodsCategory> queryWrapper = new QueryWrapper();
        queryWrapper.eq("p_id", id);
        supplierGoodsCategoryMapper.delete(queryWrapper);
        //循环添加供应商提供的分类表数据
        for (Integer i : ids) {
            SupplierGoodsCategory temp_obj = new SupplierGoodsCategory();
            temp_obj.setPId(id);
            temp_obj.setSortId(i);
            supplierGoodsCategoryMapper.insert(temp_obj);
        }
        map.put("msg", "修改成功！");
        map.put("x", true);
        return map;
    }

//    //修改供应商信息(根据多个分类id可提供的分类数据)
//    @Override
//    public Map updateSupplier_ad_id(Integer id,Integer[] ids,MultipartFile img) {
//        Map map=new HashMap();
//        //根据用户id，删除该供应商下的所有可提供的商品分类数据
//        QueryWrapper<SupplierGoodsCategory> queryWrapper=new QueryWrapper();
//        queryWrapper.eq("p_id",id);
//        supplierGoodsCategoryMapper.delete(queryWrapper);
////        List<SupplierGoodsCategory> SupplierGoodsCategory=supplierGoodsCategoryMapper.selectList(queryWrapper);
////        for(SupplierGoodsCategory s : SupplierGoodsCategory){
////            //补全属性
////            s.setName(shopTypeInfoMapper.selectById(s.getSortId()).getName());
////            //循环ids，检查
////            for(Integer i : ids){
////                if(s.getSortId()==i){
////
////                }
////            }
////        }
//        //循环添加供应商提供的分类表数据
//        for(Integer i : ids){
//            SupplierGoodsCategory temp_obj=new SupplierGoodsCategory();
//            temp_obj.setPId(id);
//            temp_obj.setSortId(i);
//            supplierGoodsCategoryMapper.insert(temp_obj);
//        }
//        map.put("msg","修改成功！");
//        map.put("x",true);
//        return map;
//    }
}
